package org.budo.shiro.session.dao.jedis;

import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.budo.support.jedis.util.JedisPoolUtil;
import org.budo.support.jedis.util.JedisUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 抽象基类
 * 
 * @author li
 * @version 1 (2015年11月9日 下午8:16:31)
 * @since Java7
 */
public abstract class AbstractBudoShiroJedisSessionDao extends AbstractSessionDAO {
    private String host = "127.0.0.1";

    private Integer port = 6379;

    private String password;

    private JedisPool jedisPool;

    private String sessionIdPrefix = "shiro-session-redis-";

    public JedisPool getJedisPool() {
        return jedisPool;
    }

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    public String getSessionIdPrefix() {
        return sessionIdPrefix;
    }

    public void setSessionIdPrefix(String sessionIdPrefix) {
        this.sessionIdPrefix = sessionIdPrefix;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Jedis getJedis() {
        if (null == this.getJedisPool()) {
            return this.newJedis();
        }

        return this.getJedisPool().getResource();
    }

    public void returnJedis(Jedis jedis) {
        if (null == this.getJedisPool()) {
            JedisUtil.close(jedis);
        } else {
            JedisPoolUtil.returnResource(this.getJedisPool(), jedis);
        }
    }

    public void returnBrokenJedis(Jedis jedis) {
        if (null == this.getJedisPool()) {
            JedisUtil.close(jedis);
        } else {
            JedisPoolUtil.returnBrokenResource(this.getJedisPool(), jedis);
        }
    }

    public Jedis newJedis() {
        Jedis jedis = new Jedis(this.getHost(), this.getPort());
        if (null != this.getPassword() && !this.getPassword().trim().isEmpty()) {
            jedis.auth(this.getPassword());
        }
        return jedis;
    }
}